﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Polaris.Domain.Interfaces.WebSite;
using Polaris.Domain.Model.DtoWebSite.Comments.Request;
using System.Security.Cryptography;
using System.Text;

namespace Polaris.WebApi.Controllers.WebSite
{
    /// <summary>
    /// Web评论控制器
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class WebCommentsController : BaseController
    {
        private readonly IWebComments _webComments;

        public WebCommentsController(IWebComments webComments)
        {
            _webComments = webComments;
        }

        /// <summary>
        /// 获取邮箱头像
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> GetEmailHead(string email)
        {
            // 处理邮箱：转为小写并去空格
            email = email.Trim().ToLower();

            string hash = "";
            // 计算 MD5 哈希
            using (var md5 = MD5.Create())
            {
                byte[] inputBytes = Encoding.UTF8.GetBytes(email);
                byte[] hashBytes = md5.ComputeHash(inputBytes);

                // 将哈希转为十六进制字符串
                var sb = new StringBuilder();
                foreach (byte b in hashBytes)
                {
                    sb.Append(b.ToString("x2"));
                }
                hash = sb.ToString();
            }
            // 生成 Gravatar URL
            return SUCCESS($"https://www.gravatar.com/avatar/{hash}?s=200&d=identicon");
        }

        /// <summary>
        /// 文章评论
        /// </summary>
        /// <param name="create"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> AuditComments(CreateCommentsRequest create)
        {
            var result = await _webComments.AuditComments(create);
            return SUCCESS(result);
        }

        /// <summary>
        /// 获取文章下的评论
        /// </summary>
        /// <param name="pageInfo"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> GetCommentsByArticle([FromQuery] CommentsPagedRequest pageInfo)
        {
            var result = await _webComments.GetCommentsByArticle(pageInfo);
            return SUCCESS(result);
        }
    }
}
